package org.csu.mypetstore.web.servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.Order;
import org.csu.mypetstore.service.OrderService;

public class ViewOrderServlet extends HttpServlet {
    private static final String VIEWORDER = "/WEB-INF/jsp/account/ViewOrder.jsp";
    private static final String ERROR = "/WEB-INF/jsp/common/Error.jsp";
    private Order order;
    private OrderService orderService;
    private Cart cart;

    public ViewOrderServlet() {
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        this.order = (Order)session.getAttribute("order");
        this.cart = (Cart)session.getAttribute("cart");
        if (this.order != null) {
            this.orderService = new OrderService();
            this.orderService.insertOrder(this.order);
            session.setAttribute("order", this.order);
            this.cart = null;
            session.setAttribute("cart", this.cart);
            session.setAttribute("message", "Thank you, your order has been submitted.");
            request.getRequestDispatcher(VIEWORDER).forward(request, response);
        } else {
            session.setAttribute("message", "An error occurred processing your order (order was null).");
            request.getRequestDispatcher(ERROR).forward(request, response);
        }

    }
}
